<?php
namespace app\beautiful\controller\miniapp\member\goods;
use app\BaseController;
use app\beautiful\logic\order\OrderLogic;
use app\beautiful\model\mall\GoodsCategoryModel;
use app\beautiful\model\mall\GoodsModel;
use app\beautiful\model\mall\GoodsSkuModel;
use app\beautiful\model\logs\GoodsViewsModel;
use think\facade\Db;

class Goods extends BaseController{
    
  
    
    
    
    
    public function getGoodsCategory()
    {
        $return = $this->getCategoryData(0);
        return $this->success($return);
    }

    protected function getCategoryData($pid=0)
    {
        $category= GoodsCategoryModel::where([
            ['shop_id','=',$this->request->shopId],
            ['is_delete','=',0],
            ['pid','=',$pid]
        ])->order(['sort'=>'desc','add_time'=>'desc'])
            ->field('category_id,name,icon')
            ->select()->toArray();
        if(!empty($category)){
            foreach ($category as $k => $v){
                $category[$k]['children']= $this->getCategoryData($v['category_id']);
            }
        }
        return $category;
    }
    
    public function getGoodsDetail(){
         $goods_id = $this->request->param('goods_id/d',0);

        if(null === $goods = GoodsModel::find($goods_id)) return $this->error('商品不存在');
        if($goods->shop_id != $this->request->shopId) return $this->error('商品不存在');
        if($goods->is_delete == 1) return $this->error('商品不存在');
        if($goods->is_open_yu != 0) return $this->error('该商品为预售商品');
        if($goods->status != 1) return $this->error('商品已下架');

        $sku=GoodsSkuModel::where([['goods_id','=',$goods_id],['is_delete','=',0]])
                ->field('sku_id,name,original_price,vip_price,quota')
                ->select()->toArray() ?? [];

        $detail=[
            'goods_id'=>$goods_id,
            'name'=>$goods->name,
            'original_price'=>$goods->original_price,
            'quota'=>$goods->quota,
            'fictitious_take_count'=>$goods->fictitious_take_count,
            'vip_price'=>$goods->vip_price,
            'is_have_sku'=>$goods->is_have_sku,
            'rotation'=>$goods->rotation,
            'goods_details'=>$goods->goods_details,
            'purchase_information' => $goods->purchase_information,
            'cover_img' => $goods->cover_img,
            'sku'=>$sku,
        ];
        //记录产品的访问记录
        $GoodsViewsModel = new GoodsViewsModel();
        $GoodsViewsModel->save([
            'shop_id'   => $this->request->shopId,
            'goods_id'  => $goods_id
        ]);
        return $this->success(['detail'=>$detail]);

    }
    
    
    
    //根据产品的ID 下发产品并以SKU 为单位
    public function getGoodsListByGoodsIds(){
        $goodsIds = $this->request->param('goods_ids/a');
        if(empty($goodsIds)){
            return $this->error('请选择要查询的产品');
        }
        foreach($goodsIds as $k=>$v){
            $goodsIds[$k] = (int)$v;
        }
        $where = [
            ['shop_id','=', $this->request->shopId],
            ['goods_id','IN', $goodsIds],
            ['is_delete','=',0],
            ['status','=',1],
        ];
        $goods = GoodsModel::with(['sku'])->where($where)
            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count')
            ->select()
            ->toArray();
        
        $returnGoods = [];
        
        foreach($goods as $val){
            $item = $val;
            if(empty($val['sku'])){
                $item['sku'] = null;
                $returnGoods[] = $item;
            }else{
                foreach($val['sku'] as $sku){
                    $item['sku'] = $sku;
                    $returnGoods[] = $item;
                }
            }
        }
        return $this->success([
            'goods' => $returnGoods
        ]);
    }
    
    
    public function getGoodsList()
    {
        $category_id=$this->request->param('category_id/d',0);
        $keyword=$this->request->param('keyword');
        $order_type=$this->request->param('order_type/d',1);

        $where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['is_open_yu','=',0],
        ];
        $return = [];
        if(!in_array($order_type,[1,2,3])) $order_type=1;
        if(!empty($category_id)){ //判断是否是父级ID 
            $category = GoodsCategoryModel::find($category_id);
            if(null !== $category){
                if($category->pid == 0){
                    $categorys = GoodsCategoryModel::where([
                        ['shop_id','=', $this->request->shopId],
                        ['pid','=', $category_id]
                    ])->column('category_id');
                    if(!empty($categorys)){
                        $categorys[] = $category_id;
                        $where[]=['category_id','IN',$categorys];
                    }else{
                        $where[]=['category_id','=',$category_id];
                    }
                }else{
                    $where[]=['category_id','=',$category_id];
                }
                $return['category'] = [
                    'category_id' => $category_id,
                    'name'        => $category->name,
                ];
            }
        }
        if(!empty($keyword)) $where[]=['name|code|purchase_information','like','%'.$keyword.'%'];

        if($order_type==1) $order=['sort'=>'desc','fictitious_take_count'=>'desc','vip_price'=>'desc'];
        if($order_type==2) $order=['fictitious_take_count'=>'desc','sort'=>'desc','vip_price'=>'desc'];
        if($order_type==3) $order=['vip_price'=>'desc','sort'=>'desc','fictitious_take_count'=>'desc'];

        $datas=GoodsModel::where($where)
            ->order($order)
            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count')
            ->limit($this->request->limit)
            ->page($this->request->page)
            ->select()
            ->toArray();
        $return['datas']=$datas;

        return $this->success($return);

    }

    public function getAllGoodsList()
    {
        $where=[
            ['shop_id','=',$this->request->shopId],
            ['status','=',1],
            ['is_delete','=',0],
            ['is_open_yu','=',0],
            ['quota','>',0],
        ];
        $order=['sort'=>'desc','fictitious_take_count'=>'desc','vip_price'=>'desc'];
        $datas= GoodsModel::with(['sku'=>function($query){
            $query->where([
                ['shop_id','=',$this->request->shopId],
                ['is_delete','=',0],
                ['quota','>',0],
                ['is_delete','=',0]
            ]);
        }])->where($where)
            ->order($order)
            ->field('goods_id,cover_img,name,original_price,vip_price,quota,take_count,fictitious_take_count,category_id')
            ->limit(500)
            ->select()
            ->toArray();
        $return['datas']=$datas;

        return $this->success($return);
    }

    public function createOrder()
    {
        $logistics_type=$this->request->param('logistics_type/d');
        $receiving_name=$this->request->param('receiving_name');
        $receiving_mobile=$this->request->param('receiving_mobile');
        $receiving_address_province=$this->request->param('receiving_address_province');
        $receiving_address_city=$this->request->param('receiving_address_city');
        $receiving_address_county=$this->request->param('receiving_address_county');
        $receiving_address_info=$this->request->param('receiving_address_info');
        $total_price = $this->request->param('total_price/f',0);
        $use_integral = $this->request->param('use_integral/d',0);
        $coupon_id = $this->request->param('coupon_id/d',0);
        $goods=$this->request->param('goods/a',[]);
        $params=[
            'member_id'=>$this->request->memberId,
            'logistics_type'=>$logistics_type,
            'receiving_name'=>$receiving_name,
            'receiving_mobile'=>$receiving_mobile,
            'receiving_address_province'=>$receiving_address_province,
            'receiving_address_city'=>$receiving_address_city,
            'receiving_address_county'=>$receiving_address_county,
            'receiving_address_info'=>$receiving_address_info,
            'total_price'=>$total_price,
            'use_integral'=>$use_integral,
            'coupon_id'=>$coupon_id,
            'goods'=>$goods,
        ];
        Db::startTrans();
        try{
            $order_logic = OrderLogic::init($this->request->shopId);
            $order_id=$order_logic['normal']->createOrder($params);
            Db::commit();
            return $this->success(['order_id'=>$order_id]);
        } catch (\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }

    }

}
